package com.atguigu.guli.service.ucenter.controller.api;

import com.atguigu.guli.service.base.JwtHelper;
import com.atguigu.guli.service.base.JwtInfo;
import com.atguigu.guli.service.result.R;
import com.atguigu.guli.service.ucenter.entity.Member;
import com.atguigu.guli.service.ucenter.service.MemberService;
import com.atguigu.guli.utils.HttpClientUtils;
import com.google.gson.Gson;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;
import java.util.UUID;

@Controller

@RequestMapping("/api/ucenter/wx")
public class WxApiMemberController {
 @Autowired
    MemberService memberService;
    //微信登录获取二维麻
    @GetMapping("/login")
    public String login(HttpSession session){
        try {
            String url ="https://open.weixin.qq.com/connect/qrconnect?" +
                    "appid=%s" +   //应用在微信注册平台的id
                    "&redirect_uri=%s" +  //回调地址
                    "&response_type=code" +
                    "&scope=snsapi_login" +
                    "&state=%s" +   //防止恶意攻击,生成随机唯一的id
                    "#wechat_redirect";
            // 拼接地址,生成二维码
            String appid = "wxed9954c01bb89b47";
            String redirectUrl = "http://localhost:8160/api/ucenter/wx/callback";
            String state = UUID.randomUUID().toString().replace("-", "").substring(0,8);
            session.setAttribute("state", state);
            url = String.format(url,appid, URLEncoder.encode(redirectUrl,"UTF-8"),state); //format 自动拼接占位符
            return  "redirect:" + url;

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            throw new RuntimeException("微信二维码生成失败");
        }
    }


     //授权后回调
    @GetMapping("/callback")
    public String collBack(@RequestParam String code,@RequestParam String state, HttpSession session){
        // 获取session中stata值,进行对比,防止恶意访问
        String wxState = (String)session.getAttribute("state");
        // 为了防止被恶意篡改,state是我们登录钱随机数生成的验证码,登录成功后微信会把这个验证码返回
        if(!StringUtils.isEmpty(state) && wxState.equals(state)) {

            try {
                String url = "https://api.weixin.qq.com/sns/oauth2/access_token?" +
                        "appid=wxed9954c01bb89b47" +  // 在微信开放平台注册,生成的id
                        "&secret=a7482517235173ddb4083788de60b90e" + // 在微信开放平台注册,生成的秘钥
                        "&code="+ code +   // 微信登录成功后,生成的code
                        "&grant_type=authorization_code";

                //发起网络请求
                HttpClientUtils client = new HttpClientUtils(url);
                client.get();
                // 获取网络请求中的参数
                String content = client.getContent();
                Gson gson = new Gson();
                // 讲网络中的参数转换为map,必须转换,微信就是以map进行存储
                Map map = gson.fromJson(content, Map.class);
                if(map.get("errcode")!= null){
                    throw  new RuntimeException("参数回显有问题");
                }
                // 成功就获取参数中的值
                Object access_token = map.get("access_token").toString(); //用户授权后,给的token
                Object openid = map.get("openid").toString();  //用户唯一id
                System.out.println(access_token);
                System.out.println(openid);
                // 根据获取的access_token和openid获取用户信息
                url = "https://api.weixin.qq.com/sns/userinfo?" +
                        "access_token="+ access_token +
                        "&openid="+ openid;
                // 发送请求
                HttpClientUtils client2 = new HttpClientUtils(url);
                client2.get();;
                // 获取请求中的参数
                String content2 = client2.getContent();
                // 变成map,因为微信的值都存在map中
                Map map2 = gson.fromJson(content2, Map.class);
                String nickname = map2.get("nickname").toString();
                Integer sex = (int)Double.parseDouble(map2.get("sex").toString());
                String headimgurl = map2.get("headimgurl").toString();

                //添加到数据库
                Member member = new Member();
                member.setAvatar(headimgurl);
                member.setSex(sex);
                member.setNickname(nickname);
                memberService.save(member);
                // 生成jwt
                JwtInfo jwtInfo = new JwtInfo();
                jwtInfo.setId(member.getId());
                jwtInfo.setNickname(nickname);
                jwtInfo.setAvatar(headimgurl);
                String token = JwtHelper.createToken(jwtInfo);
                return "redirect:http://localhost:3000?token=" + token;
            } catch (Exception e) {
                e.printStackTrace();
                throw  new RuntimeException("最终执行了错误");
            }
        }else{
            System.out.println("错误");
            throw  new RuntimeException("最终执行了错误");

        }
    }
}
